﻿using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.IO;
using Newtonsoft.Json;
using System.Linq;

namespace EcoSystem
{
    /// <summary>
    /// 
    /// </summary>
    public partial class DictionaryRequestBuinder : IModelBinder
    {
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }
            DictionaryRequestInputDto model = new DictionaryRequestInputDto();
            if (bindingContext.HttpContext.Request.Method == "POST" ||
                bindingContext.HttpContext.Request.Method == "PUT")
            {
                StreamReader stream = new StreamReader(bindingContext.HttpContext.Request.Body);
                string body = await stream.ReadToEndAsync();
                model = JsonConvert.DeserializeObject<DictionaryRequestInputDto>(body);
                if (model != null)
                {
                    model.ConvertJObjectDictonary();
                }
            }
            else
            {
                var query = bindingContext.HttpContext.Request.Query;
                foreach (var key in query.Keys)
                {
                    var values = query[key];
                    if (values.Count == 1)
                    {
                        model.TryAdd(key, values.FirstOrDefault());
                    }
                    else if (values.Count > 1)
                    {
                        model.TryAdd(key, values.ToList());
                    }
                }
            }
            bindingContext.Result = ModelBindingResult.Success(model);
            await Task.CompletedTask;
        }
    }

}
